# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _


class FapiaoApiProvider(models.Model):
    _name = "fp.api.provider"
    _description = "Fapiao Api Provider"
    _order = 'sequence, name'

    name = fields.Char(
        string='Provider name', required=True,
        help="Name of Provider, Baiwang, Aisino, etc")

    code = fields.Char(
        string='Provider Code', required=True,
        help="Code of Provider, Baiwang, Aisino, etc, Unique")

    endpoint = fields.Char(
        string='URL', required=True, help="provider URL")

    sequence = fields.Integer(default=10)

    _sql_constraints = [
        ('code_key', 'UNIQUE (code)',
         'You can not set twe api providers for the same code !')
    ]

    @api.model
    def url_get(self, code):
        one = self.search([('code', '=', code)], limit=1)
        return one.endpoint


class CompanyApiProvider(models.Model):
    _name = "fp.company.api.provider"
    _description = "Company Api Provider"

    company_id = fields.Many2one(
        'res.company', 'Company', required=True, index=True,
        default=lambda self: self.env.company)

    name = fields.Char(
        string='Name', related='company_id.name', store=True)

    @api.model
    def search_by_company(self, company_id):
        return self.search([('company_id', '=', company_id.id)], limit=1)

    _sql_constraints = [
        ('company_id_key', 'UNIQUE (company_id)',
         'You can not set two times for the same company !')
    ]


class FapiaoOperateProviderMixin(models.AbstractModel):
    _name = "fp.operate.provider.mixin"
    _description = "Fapiao Operate Provider Mixin"
    _order = 'sequence, api_provider_id'

    api_provider_id = fields.Many2one(
        'fp.api.provider', string='Api Provider')

    name = fields.Char(related='api_provider_id.name')
    code = fields.Char(related='api_provider_id.code')
    endpoint = fields.Char(related='api_provider_id.endpoint')
    sequence = fields.Integer(default=10)

    def _request_methods(self):
        # to override.
        # update other  request_method
        return {}

    def _query_methods(self):
        # to override.
        # update other  _request_read_method
        return {}

    def _request_method_get(self):
        methods = self._request_methods()
        return methods.get(self.code)

    def _query_method_get(self):
        methods = self._query_methods()
        return methods.get(self.code)


class FapiaoOperateMixin(models.AbstractModel):
    _name = "fp.fapiao.operate.mixin"
    _description = "Fapiao Operate Mixin"
    # _order = 'sequence, name'

    fapiao_id = fields.Many2one(
        'fp.fapiao', string='Fapiao',
        required=True, ondelete='restrict', index=True, copy=False,
        help="被操作的发票")

    name = fields.Char(related="fapiao_id.name")

    company_id = fields.Many2one(
        'res.company', 'Company', required=True, index=True,
        default=lambda self: self.env.company)

    user_id = fields.Many2one(
        'res.users', string='User', index=True, default=lambda self: self.env.user)

    state = fields.Selection(
        selection=[
            ('draft', 'Draft'),  # 初值
            ('doing', 'Doing'),  # 操作请求中  临时状态=等待中=返回数据
            ('done', 'done'),  # 操作完成 . 末状态  稳定状态
        ],
        string="操作控制",  default="draft", readonly=True, help="操作控制")

    @api.model_create_multi
    def create(self, vals_list):
        vals_list_with_record = []

        for vals in vals_list:
            fapiao_id = vals['fapiao_id']
            one = self.search([('fapiao_id', '=', fapiao_id)])
            vals_list_with_record.append((vals, one))
            if one:
                vals2 = vals.copy()
                del vals2['fapiao_id']
                if vals2:
                    one.write(vals2)

        vals_list_to_create = [
            vals for vals, one in vals_list_with_record if not one]

        to_create = super().create(vals_list_to_create)

        records = self.env[self._name]
        for vals, one in vals_list_with_record:
            if not one:
                one = to_create.filtered(
                    lambda r: r.fapiao_id.id == vals['fapiao_id'])
            records = records | one

        return records

    @api.model_create_multi
    def find_by_fapiao(self, fapiao):
        return self.create([{'fapiao_id': one.id} for one in fapiao])
